package com.computer.network.security.filter;

import com.computer.network.security.ex.RedisRunException;
import com.computer.network.service.SysUserService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Map;

/**
 * @author lvshiyu
 * @description: 动态权限数据源，用于获取动态权限
 * @date 2022年07月05日 17:51
 */

@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    /**
     * 权限集合
     */
    private static Map<String, ConfigAttribute> configAttributeMap = null;

    /**
     * 动态权限服务
     */
    @Resource
    SysUserService sysUserService;


    /**
     * 获取访问路径所需要的权限
     *
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取当前访问的路径
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        //获取访问该路径所需资源
        //查询当前权限属于哪个角色id
        String roleId = sysUserService.checkRole(String.valueOf(requestUrl));
        if (roleId == null) {
            throw new RedisRunException("请用户确认输入地址无误");
        }
        //返回拥有该权限的用户名
        return SecurityConfig.createList(roleId);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

}
